package com.common.config;

import com.common.base.BaseEnum;
import com.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
@PropertySource("classpath:ys.properties")
@Slf4j
public class RedisConfig {

    @Value("${redis.host}")
    private String host;

    @Value("${redis.port}")
    private int port;

    @Value("${redis.password}")
    private String password;

    @Value("${redis.timeout}")
    private int timeout;

    @Value("${redis.poolMaxTotal}")
    private int poolMaxTotal;

    @Value("${redis.poolMaxIdle}")
    private int poolMaxIdle;

    @Value("${redis.poolMaxWait}")
    private int poolMaxWait;

    @Value("${redis.blockWhenExhausted}")
    private Boolean blockWhenExhausted;

    @Bean
    public JedisPool redisPoolFactory() throws Exception {
        log.info("JedisPool注入成功！！");
        log.info("redis地址：" + host + ":" + port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(poolMaxIdle);
        jedisPoolConfig.setMaxWaitMillis(poolMaxWait);
        // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);
        return getJedisPool(jedisPoolConfig);
    }

    /**
     * 获取jedis pool
     * @param jedisPoolConfig
     * @return
     */
    private JedisPool getJedisPool(JedisPoolConfig jedisPoolConfig) {
        if (StringUtils.isEmpty(port) || StringUtils.isEmpty(host)) {
            log.error("请初始化redis配置文件");
            throw new BaseException(BaseEnum.JEDIS_HOST_TO_URL_IS_NULL);
        }
        if (StringUtils.isEmpty(password)) {
            return new JedisPool(jedisPoolConfig, host, port, timeout);
        }
        try {
            return  new JedisPool(jedisPoolConfig, host, port, timeout, password);
        }catch (Exception e){
            log.error("Jedis 注入连接异常{}",e);
        }
       return null;
    }

}
